import time

import uvicorn
from fastapi import FastAPI, BackgroundTasks
from fastapi.openapi.docs import get_swagger_ui_html
from starlette.staticfiles import StaticFiles



# 创建 FastAPI 应用实例，并把默认的/docs请求禁用
# debug表示是否开启调试模式，默认是False
app = FastAPI(docs_url=None,debug=True)
app.mount("/static", StaticFiles(directory="../static"), name="static")    # 静态文件

@app.get("/docs", include_in_schema=False)
def custom_swagger_ui():
    return get_swagger_ui_html(
        openapi_url = "/openapi.json",
        title = "Swagger UI for FastAPI",
        swagger_js_url="/static/swagger-ui-bundle.min.js",
        swagger_css_url="/static/swagger-ui.min.css"
    )

# 任务函数
def send_message(msg:str):
    print(f"start sending '{msg}'")
    # 模拟耗时
    time.sleep(10)
    print(f"finish sending '{msg}'")
    return True

@app.post("/notify")
async def send_notification(message:str,background_tasks: BackgroundTasks):
    # 添加任务
    # 第一个参数是：任务函数; 后面是需要传给它的参数
    background_tasks.add_task(send_message,msg=message)
    return {"message": f"'{message}' has been sent in background"}


if __name__ == '__main__':

    uvicorn.run("main:app", host="127.0.0.1", port=8013, reload=True)